#!/usr/bin/python
# -*-coding:utf-8-*-
# pip install ddddocr 图片识别
"""农产品质量追溯管理平台_监管机构人员"""
import math
import time
import re
from datetime import datetime, timedelta
import requests
import json
from bs4 import BeautifulSoup
from time import sleep
import common
import db
import pymongo
import sys
import random
from dotenv import load_dotenv
import os
import asyncio
from pyppeteer import launch
import numpy as np
import pandas as pd

mysqldb = db.DbManager()

load_dotenv(verbose=True)
# 今天
today_time = common.TodayTime()
# 将-替换为.
today_time_new = today_time.replace('-', '.')
# 账号
# username = "wkf674514904"
# passworld = "wkf674514904#"
username = os.getenv('ADMIN')
passworld = os.getenv('PWD')

def list_split(items, n):
    return [items[i:i + n] for i in range(0, len(items), n)]


class Egas:
    def __init__(self):
        self.url = "http://zs.jsncpaq.com/"
        root_path = "/Users/wankaifa/PycharmProjects/新思路/jsncpaq"
        with open(root_path+"/cookie.txt", 'r') as file:
            a = file.read()
            a2 = a.split("&&")
        self.cookie=a2[0]
        self.token=a2[1]
        self.org_ids = mysqldb.table_select_many(table="main_info", field="orgId", where="orgId>0 and name is null",limit=10000)
        asyncio.get_event_loop().run_until_complete(self.main())

    async def main(self):
        # 将数组 list1 每 3 个切分一次

        cookie_str = self.cookie
        cookie_str = cookie_str.encode("utf-8").decode("latin1")
        cookie_list = cookie_str.split('; ')
        cookies = {cookies.split('=')[0]: cookies.split('=')[-1] for cookies in cookie_str.split('; ')}
        headers = {
            'referer': 'https://zs.jsncpaq.com/jg/regulatorManagement.html',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_16_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3542.0 Safari/537.36',
            'token': self.token,
            'x-token': self.token,
        }
        resp = requests.get(
            "https://zs.jsncpaq.com/tracewebapp/desk/reg/pageRegulatorWorker.do?areaCodeCity=3207&pageNo=1&pageSize=2000",
            headers=headers, cookies=cookies)
        print(resp)
        json_text = json.loads(resp.text)
        print(json_text)
        list_html = json_text['rows']
        print(len(list_html))
        for i in range(0,len(list_html)):
            # 更新数据库 Regulator
            info = {"showAreaDesc": list_html[i]['showAreaDesc'],
                    "workerName":list_html[i]['workerName'],
                    "loginUserId": list_html[i]['loginUserId'],
                    'mobile':list_html[i]['mobile'],
                    'regulatorName':list_html[i]['regulatorName'],
                    'regulatorTypeName':list_html[i]['regulatorTypeName'],
                    'specialtyNames':list_html[i]['specialtyNames'],
                    'userName':list_html[i]['userName'],
                    'apiFromName':list_html[i]['apiFromName'],
                    }
            print(info)
            find_info = mysqldb.table_select_one(table="main_regulator_worker", field="id",
                                                 where={"userName": list_html[i]['userName']})
            if find_info:
                info['update_date'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                mysqldb.table_update(table="main_regulator_worker", data=info,
                                     where={"userName": list_html[i]['userName']})
            else:
                info['create_date'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                mysqldb.table_insert(table="main_regulator_worker", data=info)
Egas()
